const path = require('path');
const pack = require('../package.json');
const chalk = require('chalk');
const glob = require('glob');
const argvs = process.argv.slice(2)
const resolve = (dir) => {
    return path.join(__dirname, '..', dir)
};
const getParams = (key) => {
    let item = argvs.find(item => item.split('=')[0] === key)
    return item ? item.split('=') : []
};
const getModuleAlias = moduleName => {
    if (typeof moduleName === 'undefined') {
        moduleName = 'package';
    }
    let alias = {};
    importModules.forEach(({ name }) => {
        if (moduleName === 'package' || name === moduleName) {
            alias[`@${ name }`] = resolve(`src/modules/${ name }`);
        }
    });
    return alias
};

class MultiModule {
    constructor(name, opts) {
        let datetime = Date.now();
        Object.assign(this, {
            name,
            assetsSubDirectory: 'static',
            assetsPublicPath: '/',
            port: 8080,
            host: '0.0.0.0',
            proxyTable: null,
            entry: {
                app: [ 'babel-polyfill', `./src/modules/${ name }/main.js` ]
            },
            alias: resolve(`src/modules/${ name }`),
            index: path.resolve(__dirname, `../dist/${ name }/index.html`),
            favicon: path.resolve(__dirname, `../src/modules/${ name }/assets/favicon.ico`),
            assetsRoot: path.resolve(__dirname, `../dist/${ name }/`),
            pubdate: `${ name }_v${ pack.version }_${ datetime }`,
            deployConfig: null
        }, opts)
    }
}

const getModuleProcess = (name) => {
    if (typeof name === 'undefined') {
        name = 'package';
    }
    let mItem = importModules.find(item => item.name === name)
    return mItem || importModules[0]
};
const proxyHandle = (proxyReq, req, res, options) => {
    let origin = `${ options.target.protocol }//${ options.target.hostname }`
    proxyReq.setHeader('origin', origin)
    proxyReq.setHeader('referer', origin)
};
const onProxyReq = (proxyReq, req, res, options) => {
    proxyHandle(proxyReq, req, res, options)
};
const onProxyReqWs = (proxyReq, req, socket, options, head) => {
    proxyHandle(proxyReq, req, socket, options)
};
const getProxyConfig = (target, options) => {
    return Object.assign({
        target,
        secure: false,
        changeOrigin: true,
        ws: false,
        cookieDomainRewrite: { '*': '' },
        cookiePathRewrite: { '*': '/' },
        onProxyReq,
        onProxyReqWs
    }, options)
};
// 检测是否在输入的参数是否在允许的list中
const checkModule = () => {
    let module = process.env.MODULE_ENV;
    let moduleList = importModules.filter(item => item.name !== 'package').map(item => item.name);
    // 检查moduleList是否有重复
    let hash = {}
    let repeatList = []
    for (let l = 0; l < moduleList.length; l++) {
        if (hash[moduleList[l]]) {
            repeatList.push(moduleList[l])
        }
        hash[moduleList[l]] = true
    }
    if (repeatList.length > 0) {
        console.log(chalk.red('moduleList 有重复：'))
        console.log(chalk.red(repeatList.toString()))
        return false;
    }
    let result = true
    let illegalParam = '';
    let modules = module.replace(/，/g, ',').replace(/ /g, ',').split(',');
    for (let moduleToBuild of modules) {
        if (moduleList.indexOf(moduleToBuild) === -1) {
            result = false
            illegalParam = moduleToBuild
            break
        }
    }
    if (result === false) {
        console.log(chalk.red('参数错误，允许的参数为：'))
        console.log(chalk.green(moduleList.toString()))
        console.log(chalk.yellow(`非法参数：${ illegalParam }`))
    }
    return result;
};
// 获取当前要打包的模块列表
const getModuleToBuild = () => {
    let moduleList = importModules.filter(item => item.name !== 'package');
    let moduleToBuild = [];
    if (process.env.NODE_ENV === 'production') {
        /* 部署态，构建要打包的模块列表，如果指定了要打包的模块，那么按照指定的模块配置入口
         *  这里有个特性，即使参数未传，那么获取到的undefined也是字符串类型的，不是undefined类型
         * */
        if (process.env.MODULE_ENV !== 'undefined') {
            moduleToBuild = process.env.MODULE_ENV.replace(/，/g, ',').replace(/ /g, ',').split(',');
        } else {
            // 如果未指定要打包的模块，那么打包所有模块
            moduleToBuild = moduleList.map(item => item.name);
        }
    } else {
        // 开发态，获取所有的模块列表
        moduleToBuild = moduleList.map(item => item.name);
    }
    return moduleToBuild;
};
const PROXY_DOMAIN_DEFAULT = 'http://www.baidu.com';
// 多模块独立配置
let importModules = [];
// 自动读取模块列表
const moduleArray = glob.sync('./src/modules/*');
for (let index in moduleArray) {
    let moduleName = moduleArray[index].split('/')[3];
    if (moduleName.indexOf('.js') !== -1) {
        continue
    }
    importModules.push(new MultiModule(moduleName, {
        port: moduleName === 'package' ? 8090 : 8081,
        statics: [ 'static' ],
        proxyTable: {
            // '/servers1/': getProxyConfig(PROXY_DOMAIN_DEFAULT)
        }
    }));
}
process.env.MODULE_LIST = importModules;
let lifecycleEvents = String(process.env.npm_lifecycle_event).split(':')
let moduleName = getParams('name')[1] || lifecycleEvents[1]
if (!moduleName) {
    moduleName = 'package';
}
module.exports = {
    moduleName,
    modules: importModules,
    moduleAlias: getModuleAlias(),
    process: getModuleProcess(moduleName),
    checkModule,
    getModuleToBuild,
};
